package com.comdo.newup_loan.module.login;

import com.comdo.newup_loan.http.RetrofitHelper;
import com.comdo.newup_loan.model.LoginInfo;
import com.comdo.newup_loan.model.Result;
import com.comdo.newup_loan.util.StringUtils;
import com.google.gson.Gson;

import java.util.HashMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * Created by liyuan on 2017/10/30.
 */

class LoginPresenter extends LoginContract.Presenter{
    @Override
    public void login(String userName ,String passWord) {
        Gson gson=new Gson();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("account",userName);
        map.put("password", StringUtils.Md5(passWord) );
        map.put("sign", StringUtils.SortStringAndAddKey(map));
        String strEntity = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
        mCompositeDisposable.add(RetrofitHelper.createMyApi().login(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<LoginInfo>>() {
                    @Override
                    public void accept(Result<LoginInfo> Result) throws Exception {
                        if(Result.getCode()==1){
                            LoginInfo loginInfo=Result.getResult();
                            loginInfo.setToken(Result.getToken());
                            mView.getLoginInfo(loginInfo);

                        }else if(Result.getCode()==-3){
                            mView.loginFail("您的登陆已经失效，请重新登陆");
                            mView.exitLogin();
                        }else{
                            mView.loginFail(Result.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));
    }
}
